/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { previewer } from '@app-cad/module';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { wsApi } from '@app-cad/server';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';

type objDataType = pickedVertexData | pickedVertexData | pickedFaceData;

type FormDataType = {
  obj: objDataType;
  axis: pickedLineData;
  angle: number;
  keepSrc: boolean;
};

function SurfaceDialog({ title, onClose, props }: CurvedCmdDialogParams) {
  const { picker } = useTools();

  const initData = {
    obj: undefined,
    axis: null,
    angle: 180,
    keepSrc: true,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  // const [obj, setObj] = useState<objDataType>(undefined);

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const obj = props?.params?.base;
      const axis = props?.params?.axis;
      const keepSrc = props?.params?.keepSrc;
      await initEditDependency([obj, axis]);

      const defaultObj = obj
        ? (picker.generatePickObjByPickID(obj) as pickedVertexData)
        : undefined;
      const defaultAxis = axis
        ? (picker.generatePickObjByPickID(axis) as pickedLineData)
        : undefined;
      const defaultAngle = props?.params?.angle;
      setFormData({
        obj: defaultObj,
        axis: defaultAxis,
        angle: defaultAngle,
        keepSrc: keepSrc,
      });
      // setObj(defaultObj);
    }
  }, []);

  const checkAndFinishDraw = async () => {
    const { obj, axis, angle } = formData;
    if (isEmpty(obj) || isEmpty(axis) || angle === null) {
      return;
    }

    await execute(false);
    onClose();
  };

  const isFormDataValid = () => {
    const { obj, axis, angle } = formData;
    return obj != null && axis != null && angle != null;
  };

  const execute = async (preview: boolean) => {
    const { obj, axis, angle, keepSrc } = formData;

    const params = {
      axis: axis.edgeId,
      angle: angle,
      keepSrc: keepSrc,
    };

    if (props) {
      const res = await wsApi.setParams(
        props.shape,
        {
          base: getIdOfPickedObj(obj),
          ...params,
        },
        preview,
      );
      if (preview) {
        await previewInCommand(res);
      }
    } else {
      await confirmCommand(
        {
          a: params,
          o: getIdOfPickedObj(obj),
        },
        preview,
      );
    }
  };

  const preview = async () => {
    props ? previewer.clear() : clear();
    if (!isFormDataValid()) {
      return;
    }
    await execute(true);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      obj: {
        type: 'string',
        format: PickInputRJSFFormat.PickALL,
      },
      axis: {
        type: 'string',
        format: PickInputRJSFFormat.PickLine,
      },
      angle: {
        type: 'number',
        title: '角度',
        default: 180,
        format: NumberInputFormat.Angle,
      },
      keepSrc: {
        type: 'boolean',
        title: '显示初始元素',
        default: true,
      },
    },
  };

  const {
    initEditDependency,
    initingEdit,
    clear,
    confirmCommand,
    isLoading,
    previewInCommand,
  } = useCommand('cmd-rotate', {
    commandName: 'Rotate',
    editDxid: props?.shape,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      submitLoading={isLoading}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        const data = {
          obj: v.obj,
          axis: v.axis,
          angle: v.angle,
          keepSrc: v.keepSrc,
        };
        setFormData(data);
        // setObj(v.obj);
      }}
      extraUiSchema={{
        obj: {
          'ui:placeholder': '请输入元素',
          'ui:autofocus': true,
        },
        axis: {
          'ui:placeholder': '请输入旋转轴',
        },
        angle: {
          'ui:placeholder': '请输入角度',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdSurfaceRotate: CurvedBaseCommand = {
  id: 'CmdSurfaceRotate',
  label: 'command.rotate',
  icon: 'commands/curved/rotate',
  create: (label: string, onClose: () => void, props: any) => (
    <SurfaceDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
